<template>
  <el-form
    ref="signRef"
    size="large"
    :model="formState"
    :rules="rules"
    class="auth-form"
    label-position="top"
    hide-required-asterisk
  >
    <h1 class="auth-form__title">证书系统·精简版</h1>

    <el-form-item
      :error="accountErrorMsg"
      label="账号"
      prop="account"
      class="mb-8 mt-14"
    >
      <el-input v-model.trim="formState.account" placeholder="请输入账号或邮箱">
      </el-input>
    </el-form-item>

    <el-form-item
      :error="passwordErrorMsg"
      label="密码"
      prop="password"
      class="mb-8"
    >
      <basic-password-input
        v-model.trim="formState.password"
        placeholder="请输入密码"
        @keyup.enter="handleSubmit"
      />
    </el-form-item>

    <el-form-item>
      <el-button
        type="primary"
        class="auth-form__submit"
        :loading="loading"
        :disabled="loading"
        @click="handleSubmit"
        >登录</el-button
      >
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import type { FormInstance, FormItemRule } from 'element-plus'

import { useAppStore } from '@/stores/modules/app'

import { useSignInErrorMsg } from './useSignInErrorMsg'
interface FormState {
  account: string
  password: string
}

const loading = ref(false)
const appStore = useAppStore()
const signRef = ref<FormInstance>()

const formState = reactive<FormState>({
  account: '',
  password: ''
})

const { accountErrorMsg, passwordErrorMsg } = useSignInErrorMsg(formState)

// 校验规则
const rules: Record<keyof FormState, FormItemRule[]> = {
  account: [{ required: true, message: '请输入账号或邮箱', trigger: 'blur' }],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { validator: passwordValidate }
  ]
}
/**
 * 登录事件
 */
const handleSubmit = async () => {
  await signRef.value?.validate()
  loading.value = true
  appStore.signInAction(formState).catch(() => (loading.value = false))
}
</script>

<style scoped lang="scss">
@use './auth.scss';
</style>
